﻿using System.ComponentModel.DataAnnotations;
using System.Threading;
using AilingKit.Shared.Authorization;
using AKit.Framework.Core.Identity.Tokens;
using AKit.Framework.Core.Identity.Tokens.Models;
using AKit.Framework.Core.Identity.Users.Abstractions;
using AKit.Framework.Core.Identity.Users.Features.AssignUserRole;
using AKit.Framework.Core.Identity.Users.Features.ChangePassword;
using AKit.Framework.Core.Identity.Users.Features.ForgotPassword;
using Infrastructure.Mvc;
using Microsoft.AspNetCore.Mvc;

namespace AilingKit.WebApi.Host.Controllers;

public class UsersController : BaseController
{

    private readonly IUserService _userService;
    private readonly IHttpContextAccessor _context;

    public UsersController(IUserService userService, IHttpContextAccessor context)
    {
        _userService = userService;
        _context = context;
    }

    [HttpPost("{id:guid}/roles")]
    public async Task<IResult> AssignUserRole(string id,AssignUserRoleCommand command)
    {
        var message = await _userService.AssignRolesAsync(id, command);
        return Results.Ok(message);
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="command"></param>
    /// <returns></returns>
    [HttpPost("change-password")]
    public async Task<IResult> ChangePassword(ChangePasswordCommand command)
    {
        var userId =_context.HttpContext.User.GetUserId();
        await _userService.ChangePasswordAsync(command, userId);
        return Results.Ok("password reset email sent");
    }

    /// <summary>
    /// 邮箱确认
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="code"></param>
    /// <param name="tenant"></param>
    /// <returns></returns>
    [HttpPost("confirm-email")]
    public async Task<IResult> ChangePassword(string userId, string code, string tenant)
    {        
        return Results.Ok(await _userService.ConfirmEmailAsync(userId, code, tenant, default));
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpPost("{id:guid}")]
    public async Task<IResult> ChangePassword(string id)
    {
        await _userService.DeleteAsync(id);
        return Results.Ok();
    }

   
    /// <summary>
    /// 忘记密码
    /// </summary>
    /// <param name="tenant"></param>
    /// <param name="command"></param>
    /// <returns></returns>
    [HttpPost("forgot-password")]
    public async Task<IResult> ChangePassword([FromHeader(Name = TenantConstants.Identifier)] string tenant, ForgotPasswordCommand command)
    {
        var userId = _context.HttpContext.User.GetUserId();
        await _userService.ForgotPasswordAsync(command, userId);
        return Results.Ok();
    }
}
